package com.tangxz.sso.client.controller;

import com.tangxz.sso.core.conf.Conf;
import com.tangxz.sso.core.entity.User;
import com.tangxz.sso.core.utils.JedisUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: 唐小尊
 * @email: 1171702529@qq.com
 * @cate: 2021/07/11 21:53
 */
@Controller
public class IndexController {
    @RequestMapping("/")
    public String index(Model model, HttpServletRequest request) {
        User user = (User) request.getAttribute(Conf.SSO_USER);
        model.addAttribute(Conf.SSO_USER, user);
        return "index";
    }

    /**
     * Logout
     *
     * @param request
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(Conf.SSO_LOGOUT)
    public String logout(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(Conf.SSO_USER)) {
                    JedisUtil.del(cookie.getValue());
                    cookie.setMaxAge(0);//设置过期时间为0秒后
                    break;
                }
            }
        }
        //带参重定向
        redirectAttributes.addAttribute(Conf.REDIRECT_URL, request.getParameter(Conf.REDIRECT_URL));
        return "redirect:/";
    }
}
